<template>
  <!-- 弹框组件 -->
  <el-dialog :title="title" :visible.sync="visible" :before-close="close">
    <el-form :model="newForm">
      <el-form-item label="部门名称" :label-width="formLabelWidth">
        <el-input v-model="newForm.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="部门编号" :label-width="formLabelWidth">
        <el-input v-model="newForm.sn" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  addDepartment,
  editDepartment,
} from "../../../request/httpApi";
export default {
  props: ["title", "visible", "form"],
  data() {
    return {
      newForm: {},
      formLabelWidth: "100px"
    };
  },
  watch: {
    form(newVal, oldVal) {
      console.log(newVal, oldVal)
      // this.newForm = JSON.parse(JSON.stringify(newVal));
      this.newForm = {...newVal};
    }
  },
  methods: {
    close(reload) {
        // 关闭弹框
        // 触发自定义事件
        this.$emit('close', reload)
    },
    // 确认按钮
    submit() {
      const params = {
        name: this.newForm.name,
        sn: this.newForm.sn
        // token: localStorage.getItem("token")
      };
      if (this.newForm.id) {
        params.id = this.newForm.id;
        // 编辑
        editDepartment(params).then(res => {
          if (res.success) {
            // 关闭弹框
            this.close('reload');
            // 提示成功
            this.$message({
              message: "编辑部门成功！",
              type: "success"
            });
            // 刷新
            // this.fetchData();
          } else {
            // 提示后端返回的msg
            this.$message({
              message: res.msg || "登录失败",
              type: "error"
            });
          }
        });
      } else {
        // 添加
        addDepartment(params).then(res => {
          if (res.success) {
            // 关闭弹框
            this.close('reload');
            // 提示成功
            this.$message({
              message: "添加部门成功！",
              type: "success"
            });
            // 刷新
            // this.fetchData();
          } else {
            // 提示后端返回的msg
            this.$message({
              message: res.msg || "登录失败",
              type: "error"
            });
          }
        });
      }
    }
  }
};
</script>

<style>
</style>